#!/bin/bash
# Copyright (c) 2010, Sean A.O. Harney <sharney3@gmail.com>
# make symlinks from /usr/local/bin to this source directory


# returns 0 on success, 1 on failure
# $1 is the future symlink file name
# $2 is the symlink target's file name
function remove_and_link
{
	if [ -L "$1" ] ; then
		# it exists and is writable.
		# NOTE: mv may still fail if not file owner.
		# TODO: perhaps check with -O operator.
		TMP=`mktemp` ;
		TMP="${TMP}.${1##*/}" ;
		mv -bf "$1" "${TMP}" ;
		if [ $? -ne 0 ] ; then
			echo "Cannot proceed, could not move $1 to ${TMP} ." ;
			return 1 ;
		fi ; 
		echo "Moved $1 to backup ${TMP} ." ;
	else
	    echo "test";
	fi
	# file will not exist at this point (although it is possible
	# if multiple instances of the script were running their would
	# be a race condition), but it wouldn't be a big deal.
		
	ln -s "$2" "$1" ;
	if [ $? -ne 0 ] ; then
		echo "Cannot proceed. Could not create symlink $1 to target $2" ;
		return 1 ;
	else
		echo "Successfully created symlink $1" ;
		return 0;
	fi
}

#TODO: use $1 and $2
# start of script
remove_and_link /usr/local/bin/omf ${PWD}/src/omf && \
remove_and_link /usr/local/bin/regldg ${PWD}/src/contrib/regldg-1.0.0-base64/regldg && \
remove_and_link /usr/local/man/man1/omf.1 ${PWD}/man/omf.1 ;

exit 0 ;
